pacman::p_load(tidyverse, data.table, broom)
rm(list=ls())
################################################################################

#################################### Brazil

#Geographic units
df_un = fread("../../data/landuse/clean/geographicunits_brazil.csv.gz")[, list(county_id, amc_id, microregion_id, mesoregion_id, state_id, region, country)]

#Crop output
df = fread("../../data/landuse/clean/cropland_brazil_county.csv.gz")
setnames(df,old='crop',new='commodity')
df = df[commodity %in% c('soybean','maize','wheat','rice','sugarcane','sunflower','beans','coffee'),]
df = reshape(df, idvar = c("year", "county_id","commodity"), timevar = "variable", direction = "wide")
setnames(df,old=c('value.area_planted_ha','value.production_t','value.yield_tha','value.value_r'),new=c('area_planted_ha','production_t', 'yield_tha','value_r'))
df = merge(df_un, df, by=c('county_id'))
df_c = df[, .(production_t=sum(production_t)), by = .(year, county_id, commodity)]

#Beef output
df = fread("../../data/production/clean/cattlestock_brazil_county_ppm.csv.gz")
df_k = df[, .(stock=sum(total_cattlestock)), by = .(year)]
df_s = fread("../../data/production/clean/slaughter_brazil_nation_ptam.csv.gz")
df_sr = merge(df_s, df_k, by=c('year'))[, c('slaughter_rate','slaughter_t_h') := list(slaughter_h/stock, slaughter_t/slaughter_h ) ][, list(year, slaughter_rate, slaughter_t_h)]
df_b = merge(df, df_sr, by=c('year'))[, slaughter_h := slaughter_rate*total_cattlestock][, production_t := slaughter_h*slaughter_t_h][, commodity:='beef'][, list(year, county_id, commodity, production_t)]
df = rbind(df_c, df_b)

write.csv(df, gzfile(paste0("../../data/production/clean/production_brazil.csv.gz")), row.names = FALSE)


#################################### Argentina

#Geographic units
df_un = fread("../../data/landuse/clean/geographicunits_argentina.csv.gz")[, list(county_id, state_id, region, country)]

#Crop output
df = fread("../../data/landuse/clean/cropland_argentina_county.csv.gz")
setnames(df,old='crop',new='commodity')
df = df[commodity %in% c('soybean','maize','wheat','rice','sugarcane','sunflower','beans','coffee'),]
df_c = df[, .(production_t=sum(production_t)), by = .(year, county_id, commodity)]

write.csv(df_c, gzfile(paste0("../../data/production/clean/production_argentina.csv.gz")), row.names = FALSE)


